//
//  KLNetWorkService.m
//  KLCurrency
//
//  Created by apple on 2018/1/4.
//  Copyright © 2018年 bonc. All rights reserved.
//

#import "KLNetWorkService.h"

#import "KLCurrencyHelper.h"
#import "KLCurrencyService.h"

#import "AFNetworking.h"

@interface KLNetWorkService ()

@end

@implementation KLNetWorkService


static AFHTTPSessionManager *manager ;

+ (AFHTTPSessionManager *)sharedHTTPSession {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = kCurrencyLayerRequestTimeOut;
    });
    return manager;
}

+ (void)getCurrencyLayerLiveRateWithSuccess:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure {
    
    AFHTTPSessionManager *manager = [[self class] sharedHTTPSession];
    NSDictionary *getParamDic = @{
                                  @"access_key":kCurrencyLayerKey,
                                  };
    [manager GET:kCurrencyLayerLiveUrl parameters:getParamDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        BOOL requestSuc = dic[@"success"];
        if (requestSuc) {
            NSDictionary *resultDic = dic[@"quotes"];
            KLLog(@"正确返回报文(最新汇率):%@",resultDic);
            if (success) {
                success(resultDic);
            }
        } else {
            NSDictionary *errorDic = dic[@"error"];
            NSString *error = errorDic[@"info"];
            if (failure) {
                failure(error);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.description);
        }
    }];
}

+ (void)testCurrencyLayerHistoricalRatesWithExchangeCurrency:(NSString *)cur1 localCurrency:(NSString *)cur2 datePeriod:(NSArray<NSString *> *)dates success:(void (^)(NSArray<KLHistoricalRate *> *))success failure:(void (^)(NSString *))failure {
    
      if (![cur1 isEqualToString:cur2]) {
          NSMutableArray *tempRateEntityArr = [NSMutableArray array];
          
          NSUInteger dateLength = dates.count;
          //获取近一年多的美元转人民币数据
          NSArray *defaultHistoryRateFromUSDToCNYArr = [KLCurrencyHelper defaultHistoryRateFromUSDToCNY];
          //获取对应时间段数据
          NSArray *rangedHistoryRateFromUSDToCNYArr = [defaultHistoryRateFromUSDToCNYArr subarrayWithRange:NSMakeRange(defaultHistoryRateFromUSDToCNYArr.count - dateLength, dateLength)];
          NSDictionary *rateDic = [KLCurrencyService getExchangeRateDictionary];
          //转换成对应货币需要的量
          double rateTrans = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:rateDic]/[KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:@"USD" toCurrency2:@"CNY" rateDictionary:rateDic];
          
          for (NSUInteger ii = 0; ii<dateLength; ii++) {
              KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
              rateEntity.date = dates[ii];
              rateEntity.rate = [rangedHistoryRateFromUSDToCNYArr[ii] doubleValue] * rateTrans;
              [tempRateEntityArr addObject:rateEntity];
          }
          
          NSArray *result = [tempRateEntityArr mutableCopy];
          dispatch_async(dispatch_get_main_queue(), ^{
              if (success) {
                  success(result);
              }
          });
      } else {
          //前后查询货币一致 直接rate设为1
          NSMutableArray *tempRateEntityArr = [NSMutableArray array];
          for (NSString *date in dates) {
              KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
              rateEntity.date = date;
              rateEntity.rate = 1.0000;
              [tempRateEntityArr addObject:rateEntity];
          }
          
          NSArray *result = [tempRateEntityArr mutableCopy];
          dispatch_async(dispatch_get_main_queue(), ^{
              if (success) {
                  success(result);
              }
          });
      }
}


+ (void)getCurrencyLayerHistoricalRatesWithExchangeCurrency:(NSString *)cur1 localCurrency:(NSString *)cur2 datePeriod:(NSArray<NSString *> *)dates success:(void (^)(NSArray<KLHistoricalRate *> *))success failure:(void (^)(NSString *))failure {
    
    if (![cur1 isEqualToString:cur2]) {
        
//        __block KLHistoricalRate *rateEntity0 = [[KLHistoricalRate alloc] init];
//        __block KLHistoricalRate *rateEntity1 = [[KLHistoricalRate alloc] init];
//        __block KLHistoricalRate *rateEntity2 = [[KLHistoricalRate alloc] init];
//        __block KLHistoricalRate *rateEntity3 = [[KLHistoricalRate alloc] init];
//        __block KLHistoricalRate *rateEntity4 = [[KLHistoricalRate alloc] init];
//        __block KLHistoricalRate *rateEntity5 = [[KLHistoricalRate alloc] init];
//
//        dispatch_group_t group = dispatch_group_create();
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[0];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第0个数据");
//                    rateEntity0.date = queryDate;
//                    rateEntity0.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[1];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第1个数据");
//                    rateEntity1.date = queryDate;
//                    rateEntity1.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[2];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第2个数据");
//                    rateEntity2.date = queryDate;
//                    rateEntity2.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[3];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第3个数据");
//                    rateEntity3.date = queryDate;
//                    rateEntity3.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[4];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第4个数据");
//                    rateEntity4.date = queryDate;
//                    rateEntity4.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//
//            NSString *queryDate = dates[5];
//
//            NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,queryDate];
//            NSURL *url = [NSURL URLWithString:urlStr];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//
//            if (data) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                BOOL requestSuc = dic[@"success"];
//                if (requestSuc) {
//                    NSDictionary *resultDic = dic[@"quotes"];
//                    //            KLLog(@"正确返回报文:%@",resultDic);
//                    KLLog(@"第5个数据");
//                    rateEntity5.date = queryDate;
//                    rateEntity5.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                }
//            }
//        });
//
//        //group全部采集完成后回调主线程
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//                NSArray *entityArr = @[
//                                       rateEntity0,
//                                       rateEntity1,
//                                       rateEntity2,
//                                       rateEntity3,
//                                       rateEntity4,
//                                       rateEntity5,
//                                       ];
//                if (success) {
//                    success(entityArr);
//                }
//            });
//        });
        
        
        dispatch_group_t group = dispatch_group_create();
        __block NSMutableArray *tempRateEntityArr = [NSMutableArray array];
        for (NSString *date in dates) {
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //rate 查询
                //method1:AFN syn with semaphore
                AFHTTPSessionManager *manager = [[self class] sharedHTTPSession];
                NSDictionary *getParamDic = @{
                                              @"access_key":kCurrencyLayerKey,
                                              @"date":date,
                                              };
                dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
                [manager GET:kCurrencyLayerHistoricalUrl parameters:getParamDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = responseObject;
                    BOOL requestSuc = dic[@"success"];
                    if (requestSuc) {
                        NSDictionary *resultDic = dic[@"quotes"];
                        //            KLLog(@"正确返回报文:%@",resultDic);
                        KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
                        rateEntity.date = date;
                        rateEntity.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
                        KLLog(@"历史数据: %@---%.6f",date,rateEntity.rate);
                        [tempRateEntityArr addObject:rateEntity];
                        dispatch_semaphore_signal(semaphore);   //发送信号
                    } else {
                        NSDictionary *errorDic = dic[@"error"];
                        NSString *error = errorDic[@"info"];
                        if (failure) {
                            failure(error);
                        }
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    if (failure) {
                        failure(error.description);
                    }
                }];
                dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);  //等待
                KLLog(@"数据加载完成！");
                //method2:NSURLSession syn with semaphore
//                NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,date];
//                NSURL *url = [NSURL URLWithString:urlStr];
//                dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//                [request setHTTPMethod:@"GET"];
//                [request setTimeoutInterval:60];
//                NSURLSession *session = [NSURLSession sharedSession];
//
//                NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//                    if (data) {
//                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                        BOOL requestSuc = dic[@"success"];
//                        if (requestSuc) {
//                            NSDictionary *resultDic = dic[@"quotes"];
//                            //            KLLog(@"正确返回报文:%@",resultDic);
//                            KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
//                            rateEntity.date = date;
//                            rateEntity.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                            KLLog(@"历史数据: %@---%.6f",date,rateEntity.rate);
//                            [tempRateEntityArr addObject:rateEntity];
//                            dispatch_semaphore_signal(semaphore);   //发送信号
//                        }
//                    }
//                }];
//                [task resume];
//                dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);  //等待
//                KLLog(@"数据加载完成！");
                
                //method3:data with syn
//                NSString *urlStr = [NSString stringWithFormat:@"%@?access_key=%@&date=%@&format=1",kCurrencyLayerHistoricalUrl,kCurrencyLayerKey,date];
//                NSURL *url = [NSURL URLWithString:urlStr];
//                NSData *data = [NSData dataWithContentsOfURL:url];
//                if (data) {
//                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//                    BOOL requestSuc = dic[@"success"];
//                    if (requestSuc) {
//                        NSDictionary *resultDic = dic[@"quotes"];
//                        //            KLLog(@"正确返回报文:%@",resultDic);
//                        KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
//                        rateEntity.date = date;
//                        rateEntity.rate = [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:cur1 toCurrency2:cur2 rateDictionary:resultDic];
//                        KLLog(@"历史数据: %@---%.6f",date,rateEntity.rate);
//                        [tempRateEntityArr addObject:rateEntity];
//                    }
//                }
            });
        }
        
        //全部采集完成 group回调 检查查询数据的数量与顺序
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *tempRateEntityArr2 = [NSMutableArray array];
                for (int i = 0 ; i< dates.count; i++) {
                    for (KLHistoricalRate *entity in tempRateEntityArr) {
                        if ([dates[i] isEqualToString:entity.date]) {
                            [tempRateEntityArr2 addObject:entity];
                        }
                    }
                }
                NSArray *result = [tempRateEntityArr2 mutableCopy];
                if (success) {
                    success(result);
                }
            });
        });
    } else {
        //前后查询货币一致 直接rate设为1
        NSMutableArray *tempRateEntityArr = [NSMutableArray array];
        for (NSString *date in dates) {
            KLHistoricalRate *rateEntity = [[KLHistoricalRate alloc] init];
            rateEntity.date = date;
            rateEntity.rate = 1.0000;
            [tempRateEntityArr addObject:rateEntity];
        }
        NSArray *entityArr = [tempRateEntityArr mutableCopy];
        if (success) {
            success(entityArr);
        }
    }
}




@end
